#include"../../include/TcpClinet.h"
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<iostream>
using namespace std;
TcpClinet::TcpClinet(const string &ip,unsigned short port)
:_sok(),
_sokIO(_sok.fd()),
_dstAddr(ip,port),
_isConn(false)
{

}

TcpClinet::~TcpClinet()
{

}


void TcpClinet::connect()
{
    if(!_isConn)
    {
        socklen_t len = sizeof(struct sockaddr_in);
        int ret = ::connect(_sok.fd(),(struct sockaddr*)_dstAddr.getInetAddrPtr(),len);
        if(ret)
        {
            perror("connect");
            return ;
        }
        _isConn = true;
        cout<<"connect is ok"<<endl;
    }
}

string TcpClinet::recvMsg()
{
    //协议的封装
        char buf[65535]={0};
        int len = 0;
        int ret = _sokIO.readn((char*)&len,4);
        if(ret == 0)
        {
            cout<<"recv failed!"<<endl;
            _isConn = false;
            return string();
        }
        ret = _sokIO.readn(buf,len);
        if(ret == 0)
        {
            cout<<"recv failed!"<<endl;
            _isConn = false;
            return string();
        }
        return string(buf);
}

void TcpClinet::sendMsg(const string &data,int flag)
{
    //协议的封装
    char buf[1500]={0};
    memcpy(buf,&flag,4);
    int len = data.size();
    memcpy(buf+4,&len,4);
    memcpy(buf+8,data.c_str(),data.size());

    int ret = _sokIO.writen(buf,8+data.size());
    if(ret == 0)
    {
        _isConn = false;
    }
}

bool TcpClinet::isConnection()
{
    return _isConn;
}